#include <stdio.h>

// Extended GCD function from "Cryptography Engineering" (p112)
int extendedGCD(int a, int b, int *k, int *u, int *v) {
    int u1 = 1, u3 = a;
    int v1 = 0, v3 = b;
    int temp;

    while (v3 != 0) {
        int q = u3 / v3;
        temp = u1; u1 = v1; v1 = temp - q * v1;
        temp = u3; u3 = v3; v3 = temp - q * v3;
    }

    *k = u3;
    *u = u1;
    *v = (u3 - a * u1) / b;

    return u3;
}

// Function to calculate modular inverse
int modInverse(int a, int m) {
    int k, u, v;
    int gcd = extendedGCD(a, m, &k, &u, &v);

    if (gcd != 1) {
        printf("Inverse does not exist.\n");
        return -1;  // No modular inverse
    } else {
        // Ensure u is positive
        u = (u % m + m) % m;
        return u;
    }
}

int main() {
    int a = 74;
    int m = 167;

    // Calculate modular inverse of a modulo m
    int inverse = modInverse(a, m);

    if (inverse != -1) {
        printf("The modular inverse of %d modulo %d is: %d\n", a, m, inverse);
    }

    // Additional test cases
    int a2 = 17;
    int m2 = 31;

    int inverse2 = modInverse(a2, m2);

    if (inverse2 != -1) {
        printf("The modular inverse of %d modulo %d is: %d\n", a2, m2, inverse2);
    }

    int a3 = 15;
    int m3 = 26;

    int inverse3 = modInverse(a3, m3);

    if (inverse3 != -1) {
        printf("The modular inverse of %d modulo %d is: %d\n", a3, m3, inverse3);
    }

    return 0;
}

